﻿#include "shapelibrarypanel.h"
#include "IShape.h"
#include "ShapeFactory.h"
#include <QLabel>
#include <QPainter>
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>
#include <qDebug>


// 自定义形状Widget（实现绘图和拖拽）
class ShapeWidget : public QWidget
{
public:
    ShapeWidget(const QString& name, QWidget* parent = nullptr)
        : QWidget(parent), m_name(name)
    {
        setEnabled(true); // 确保控件是启用的
        setFixedSize(80, 80);
        setToolTip(tr(m_name.toUtf8().constData()));
        setCursor(Qt::OpenHandCursor);

        // 创建预览图形
        m_previewShape = ShapeFactory::instance().create(m_name);  
    }

protected:
    void paintEvent(QPaintEvent*) override {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);

        // 统一灰色背景
        //painter.fillRect(rect(), QColor(240, 240, 240));

        if (m_previewShape) {
            // 保存状态并应用预览变换
            painter.save();
            
            // 设置预览样式
            QPen pen(Qt::black, 2);
            painter.setPen(pen);
            painter.setBrush(Qt::NoBrush);

            // 绘制预览图形
            m_previewShape->paint(painter);
            painter.restore();
        }
    }

    void mousePressEvent(QMouseEvent* event) override {
        if (event->button() == Qt::LeftButton) {
            QDrag* drag = new QDrag(this);
            QMimeData* mime = new QMimeData();

            // 创建携带的数据（类型和偏移量）
            QByteArray itemData;
            QDataStream stream(&itemData, QIODevice::WriteOnly);
            stream << m_name << event->pos();

            mime->setData("application/x-shape", itemData);

            // 创建拖拽缩略图
            QPixmap pixmap(size());
            render(&pixmap);
            drag->setPixmap(pixmap);
            drag->setHotSpot(event->pos());
            drag->setMimeData(mime);

            drag->exec(Qt::CopyAction);
        }
        QWidget::mousePressEvent(event);
    }

private:
    QString m_name;
    std::unique_ptr<IShape> m_previewShape;
};

// ==================== ShapeLibraryPanel实现 ====================
ShapeLibraryPanel::ShapeLibraryPanel(QWidget* parent)
    : QWidget(parent)
{
    setupUI();
    m_shapeNames = ShapeFactory::instance().availableShapes();
    registerShape();
}

void ShapeLibraryPanel::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(5, 5, 5, 5);
    mainLayout->setSpacing(10);

    // 标题
    QLabel* titleLabel = new QLabel(tr("Shape Library"));
    
    mainLayout->addWidget(titleLabel);

     //搜索框
    m_searchBox = new QLineEdit();
    m_searchBox->setPlaceholderText(tr("Search shapes..."));
    //m_searchBox->setStyleSheet("padding: 5px;");
    connect(m_searchBox, &QLineEdit::textChanged, this, &ShapeLibraryPanel::onSearchTextChanged);
    mainLayout->addWidget(m_searchBox);

    //// 可滚动区域
    m_scrollArea = new QScrollArea();
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); 

    m_container = new QWidget();
    m_gridLayout = new QGridLayout(m_container);
    m_gridLayout->setSpacing(10);
    m_gridLayout->setAlignment(Qt::AlignTop);

    m_scrollArea->setWidget(m_container);
    mainLayout->addWidget(m_scrollArea);
    m_scrollArea->viewport()->setStyleSheet("background: transparent;");
    
}

//创建所以图像的Qwidget
void ShapeLibraryPanel::registerShape()
{
    m_shapeNames.erase(
        std::remove(m_shapeNames.begin(), m_shapeNames.end(), "Line"),
        m_shapeNames.end()
    );
    for (auto name : m_shapeNames)
    {
        m_shapeWidgets.append(createShapeWidget(name));
    }

    updateGridLayout();
}

QWidget* ShapeLibraryPanel::createShapeWidget(const QString& name)
{
    return new ShapeWidget(name, m_container);
}

void ShapeLibraryPanel::updateGridLayout()
{
    // 清除旧布局
    while (m_gridLayout->count() > 0) {
        QLayoutItem* item = m_gridLayout->takeAt(0);
        
        delete item;
    }

    // 计算列数
    m_columns = qMax(1, width() / (m_widgetSize.width() + m_gridLayout->spacing()));

    // 重新排列
    int row = 0, col = 0;
    for (QWidget* widget : m_shapeWidgets) {
        if (widget->isVisible()) {
            m_gridLayout->addWidget(widget, row, col);
            if (++col >= m_columns) {
                col = 0;
                row++;
            }
        }
    }
}

void ShapeLibraryPanel::resizeEvent(QResizeEvent* event)
{
    qDebug() << "Panel size:" << size();
    qDebug() << "ScrollArea viewport size:" << m_scrollArea->viewport()->size();
    QWidget::resizeEvent(event);
    updateGridLayout();
}

void ShapeLibraryPanel::onSearchTextChanged(const QString& text)
{
    for (int i = 0; i < m_shapeNames.size(); ++i) {
        bool match = m_shapeNames[i].contains(text, Qt::CaseInsensitive);
        m_shapeWidgets[i]->setVisible(match);
    }
    updateGridLayout();
}